package org.mebusw.davincicode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Random;

import org.mebusw.davincicode.vo.DavinciCard;

/**
 * @author j1shen
 * @see DavinciCard
 * @see PlayerManager
 */
public class CardPoolManager {
	private ArrayList<DavinciCard> cards;

	public CardPoolManager() {
	}

	public CardPoolManager(ArrayList<DavinciCard> list) {
		this.cards = list;
	}

	public void initPool(boolean expansion) {
		DavinciCard card = null;

		cards.clear();
		for (int i = 0; i <= 11; i++) {
			// black card
			card = new DavinciCard(DavinciCard.BLACK, i, DavinciCard.NONJOKER,
					DavinciCard.UNKNOWN_CARDID, DavinciCard.MASKED,
					DavinciCard.IN_POOL);
			cards.add(card);
			// white card
			card = new DavinciCard(DavinciCard.WHITE, i, DavinciCard.NONJOKER,
					DavinciCard.UNKNOWN_CARDID, DavinciCard.MASKED,
					DavinciCard.IN_POOL);
			cards.add(card);
		}

		if (expansion) {
			// the two jokers
			card = new DavinciCard(DavinciCard.BLACK, DavinciCard.JOKER99,
					DavinciCard.JOKER, DavinciCard.UNKNOWN_CARDID,
					DavinciCard.MASKED, DavinciCard.IN_POOL);
			cards.add(card);
			card = new DavinciCard(DavinciCard.WHITE, DavinciCard.JOKER99,
					DavinciCard.JOKER, DavinciCard.UNKNOWN_CARDID,
					DavinciCard.MASKED, DavinciCard.IN_POOL);
			cards.add(card);
		}

		Collections.shuffle(cards);

		for (int i = 0; i < cards.size(); i++) {
			card = (DavinciCard) cards.get(i);
			card.setCardId(i);
			card.setOwner(DavinciCard.IN_POOL);
		}
		System.out.println("cardpool.init(): " + cards.size());
	}

	/**
	 * player takes one card randomly from the pool on the table and a card Id
	 * will be given
	 * 
	 * @return DavinciCard
	 * @see PlayerManager
	 */
	public DavinciCard randTake() {

		DavinciCard card = null;
		Date t = new Date(System.currentTimeMillis());
		Random rand = new Random(t.getTime());

		if (cards.size() <= 0)
			return null;
		try {
			int index = rand.nextInt(cards.size());
			card = (DavinciCard) cards.get(index);
			cards.remove(index);
		} catch (Exception e) {
			System.out.println("CardPool.randTake(): " + e);
		}

		return card;
	}

	public void clear() {
		cards.clear();
	}

	/**
	 * simply return card pool's size.
	 * 
	 * @return cards.size()
	 */
	public int size() {
		return cards.size();
	}

	public ArrayList<DavinciCard> getCards() {
		return cards;
	}

	public void setCards(ArrayList<DavinciCard> cards) {
		this.cards = cards;
	}

}
